package com.usian.comment.service.impl;

import com.usian.comment.feign.UserFeign;
import com.usian.comment.service.CommentService;
import com.usian.model.comment.dto.CommentDto;
import com.usian.model.comment.dto.CommentSaveDto;
import com.usian.model.comment.pojos.ApComment;
import com.usian.model.comment.pojos.ApCommentLike;
import com.usian.model.comment.pojos.ApCommentVo;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.user.pojos.ApUser;
import com.usian.utils.threadlocal.AppThreadLocalUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CommentServiceImpl implements CommentService {

    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private UserFeign userFeign;

    @Override
    public ResponseResult saveApComment(CommentSaveDto dto) {

        //1:校验参数
        if (dto.getArticleId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        if (dto.getContent() != null && dto.getContent().length() > 140) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE, "评论内容不能超过140字");
        }

        //2:获取用户昵称
        ApUser user = AppThreadLocalUtils.getUser();
        if(user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        ApUser apUser = userFeign.findUserById(user.getId());
        if(apUser==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        //3:monggo 保存评论信息
        ApComment apComment = new ApComment();
        apComment.setAuthorId(apUser.getId());
        apComment.setAuthorName(apUser.getName());
        apComment.setContent(dto.getContent());
        apComment.setEntryId(dto.getArticleId());
        apComment.setCreatedTime(new Date());
        apComment.setUpdatedTime(new Date());
        apComment.setImage(apUser.getImage());
        apComment.setLikes(0);
        apComment.setReply(0);
        apComment.setType((short) 0);
        apComment.setFlag((short) 0);
        mongoTemplate.save(apComment);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult findByArticleId(CommentDto dto) {

        if(dto.getArticleId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        //1:根据文章id查询这篇文章有那些评论
        Query query=new Query();
        query.addCriteria(Criteria.where("entryId").is(dto.getArticleId()).and("createdTime").lt(dto.getMinDate()))
                .limit(3).with(Sort.by(Sort.Direction.DESC,"createdTime"));
        List<ApComment> commentList = mongoTemplate.find(query, ApComment.class);

        //['80esdfsesdsfsdsd','df2edsfw3sdfwesd'...]
        // select * from apcommentLike  where commentId in（list）
        List<String> commentIdList = commentList.stream().map(a -> a.getId()).collect(Collectors.toList());

        ApUser user = AppThreadLocalUtils.getUser();
        if(user ==null){
            return ResponseResult.okResult(commentList);
        }

        //2:根据文章id查询like 评论点赞信息
        Query query1=new Query();
        query1.addCriteria(Criteria.where("commentId").in(commentIdList).and("authorId").is(user.getId()));
        List<ApCommentLike> commentLikeList = mongoTemplate.find(query1, ApCommentLike.class);


        //3：比较我评论那些文章
        List<ApCommentVo> resultList = new ArrayList<>();

        //4:登录和非登录返回的结果不一样  登录返回是我评论或点赞过的评论    未登录那就直接返回默认所有评论
        if(commentList!=null && commentLikeList!=null){
            //用户登录
            commentList.stream().forEach(c ->{
                ApCommentVo av =new ApCommentVo();
                BeanUtils.copyProperties(c,av);
                for(ApCommentLike al :commentLikeList){

                    if(c.getId().equals(al.getCommentId())){
                        //一致 是我点赞过评论过的文章
                        av.setOperation((short)0);
                        break;
                    }
                }
                resultList.add(av);
            });
            return ResponseResult.okResult(resultList);
        }else{
            return ResponseResult.okResult(commentList);
        }
    }


}
